package top.lixunda.common.validate.validate;

import lombok.extern.slf4j.Slf4j;
import top.lixunda.common.validate.annotation.XumDefault;
import top.lixunda.common.validate.core.ValidateError;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

/**
 * @author Xumda
 * @version time:2019/12/9 13:15
 * <p>
 * 设置默认值
 */
@Slf4j
public class DefaultValidate implements AnnotationValidate {

    @Override
    public boolean support(Class annotationClass) {
        return XumDefault.class.equals(annotationClass);
    }

    @Override
    public ValidateError valid(Annotation annotation, Field field, Object obj, Object value, AnnotationCacheValidate handler) {
        // 获取值
        XumDefault a = (XumDefault) annotation;
        boolean isNull = (value == null || (value instanceof String && "".equals(value)));
        if (!isNull) {
            return null;
        }
        field.setAccessible(true);
        String type = field.getType().getName();
        try {
            switch (type) {
                case Type.STRING:
                    field.set(obj, String.valueOf(a.value()[0]));
                    break;
                case Type.CHAR:
                    field.set(obj, (char) a.numbers()[0]);
                    break;
                case Type.SHORT:
                    field.set(obj, (short) a.numbers()[0]);
                    break;
                case Type.INTEGER:
                    field.set(obj, (int) a.numbers()[0]);
                    break;
                case Type.LONG:
                    field.set(obj, a.numbers()[0]);
                    break;
                case Type.FLOAT:
                    field.set(obj, (float) a.doubleNumbers()[0]);
                    break;
                case Type.DOUBLE:
                    field.set(obj, a.doubleNumbers()[0]);
                    break;
                default:
                    log.warn("暂不支持的类型");
            }
        } catch (IllegalAccessException e) {
            log.error("注入默认值失败");
            e.printStackTrace();
        }
        return null;
    }


}
